<template>
  <el-button type="primary" @click="openDialog">编辑任务</el-button>
  <el-dialog
    v-model="dialogVisible"
    title="编辑任务"
    width="1500"
    :before-close="handleClose"
  >
    <div class="data-editor-container">
      <div class="custom-tree-container">
        <el-button type="primary" size="small" @click="addNewTask"
          >新增任务</el-button
        >
        <el-tree
          style="max-width: 600px; margin-top: 20px"
          :data="dataSource"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          @node-click="treeNodeClick"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <NameCell
                :label="node.label"
                @change="(v) => changeLabel(node, data, v)"
              />
              <!-- <el-input :value="node.label" @change="(v) => (data.label = v)" /> -->
              <span>
                <a @click="append(data)"> Append </a>
                <a style="margin-left: 8px" @click="remove(node, data)">
                  Delete
                </a>
              </span>
            </span>
          </template>
        </el-tree>
      </div>
      <div class="plans-container" v-if="_selected">
        <el-button type="primary" size="small" @click="addNewPlan"
          >新增计划</el-button
        >
        <el-table :data="_selected.plans" style="width: 100%" max-height="650">
          <el-table-column fixed prop="start" label="开始" width="150">
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.start"
                type="date"
                placeholder="Pick a day"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column fixed prop="end" label="结束" width="250">
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.end"
                type="date"
                placeholder="Pick a day"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column fixed prop="desc" label="描述">
            <template #default="scope">
              <el-input v-model="scope.row.desc" size="small" />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="scope">
              <el-button
                link
                type="danger"
                size="small"
                @click.prevent="deletePlan(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirmClick"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw, defineEmits, defineProps } from "vue";
import type Node from "element-plus/es/components/tree/src/model/node";
import { ElMessageBox } from "element-plus";
import NameCell from "./data.name.vue";
import { generateUUID } from "./utils/uuid";
import moment from "moment";
import Adapter from "./gantt.adapter";
import { RuleTester } from "eslint";

const emit = defineEmits(["confirm"]);

interface Plan {
  id: string;
  start: string;
  end: string;
  desc: string;
}

interface Tree {
  id: number;
  label: string;
  plans?: Plan[];
  children?: Tree[];
}

const props = defineProps({
  adapter: Adapter,
});

const genTaskId = () => {
  return generateUUID("task");
};
const genPlanId = () => {
  return generateUUID("plan");
};

const dataSource = reactive([]);
const _selected = ref(null);
const dialogVisible = ref(false);

function openDialog() {
  dialogVisible.value = true;
  dataSource.splice(0, dataSource.length);
  let datas = props.adapter.data;
  datas.forEach((d) => {
    dataSource.push(d);
  });
}

function addNewTask() {
  dataSource.push({
    id: genTaskId(),
    label: "testtest",
    children: [],
    plans: [],
  });
}

const handleClose = (done: () => void) => {
  done();
};

const append = (data: Tree) => {
  const newChild = {
    id: genTaskId(),
    label: "testtest",
    children: [],
    plans: [],
  };
  if (!data.children) {
    data.children = [];
  }
  data.children.push(newChild);
};

const remove = (node: Node, data: Tree) => {
  const parent = node.parent;
  const children: Tree[] = parent.data.children || parent.data;
  const index = children.findIndex((d) => d.id === data.id);
  children.splice(index, 1);
};

const changeLabel = (node: Node, data: Tree, label: string) => {
  const parent = node.parent;
  const children: Tree[] = parent.data.children || parent.data;
  const index = children.findIndex((d) => d.id === data.id);
  if (index !== -1) {
    let m = children[index];
    m.label = label;
    children.splice(index, 1, m);
  }
};

function treeNodeClick(d) {
  console.log("treeNodeClick", d.label);
  if (!d || d.id === -1) return;
  _selected.value = d;
}

function confirmClick() {
  let list = toRaw(dataSource);
  console.log("list", list);
  props.adapter.data = list.slice();
  dialogVisible.value = false;
  emit("confirm");
}

function addNewPlan() {
  let node = _selected.value;
  if (!node) return;

  let plan = {
    id: genPlanId(),
    start: moment().format("YYYY-MM-DD"),
    end: moment().add(3, "days").format("YYYY-MM-DD"),
    desc: "",
  };

  if (!node.plans) {
    node.plans = [];
  }

  node.plans.push(plan);
}

function deletePlan(plan) {
  let node = _selected.value;
  if (!node) return;
  if (!node.plans) {
    node.plans = [];
  }
  let index = node.plans.findIndex((p) => p.id === plan.id);
  if (index !== -1) {
    node.plans.splice(index, 1);
  }
  //   console.log("deletePlan", plan);
}
</script>

<style>
.custom-tree-container {
  height: 100%;
  overflow: auto;
  width: 600px;
  border: 1px solid red;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.data-editor-container {
  width: 100%;
  display: flex;
  height: 700px;
}
.plans-container {
  height: 100%;
  flex: 1;
  overflow: auto;
  border: 1px solid orange;
}
</style>